//
//  DepoistTypeListHeadCell.swift
//  d11
//
//  Created by peale on 2018/10/20.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit

class DepoistTypeListHeadCell: UITableViewCell,UITextFieldDelegate {
    var bgImgView : UIImageView?
//    var iconImgView : UIImageView?
//     var lineLView : UIView?
//    var titleLabel : UILabel?
//    var lineRView : UIView?
    var editMoney : UITextField?
    var bgItemView : UIView?
    var bgItemBtn : UIButton?
    var itemIconImgView : UIImageView?
    var itemTitleLabel : UILabel?
    var arrowImgView : UIImageView?
    var lineView : UIView?
    weak var delegate : EndEidtDelegate?
    var task : Task?
    var tagImageView : UIImageView?
       var tagName : UILabel?
       var tagView : UIView?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUpUI()
    }
    func makeTimer(){
        
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setUpUI() -> Void {
        self.backgroundColor  = UIColor.white
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        
        var image = UIImage(named: "icon_depoist_type_list_head_bg2")
        let leftCapWidth: Int = Int(image!.size.width / 2)   // 取图片Width的中心点
        let topCapHeight: Int = Int(image!.size.height / 2)  // 取图片Height的中心点
        image = image?.stretchableImage(withLeftCapWidth: leftCapWidth, topCapHeight: topCapHeight)
//        let image = UIImage(named: "icon_depoist_type_list_head_bg2")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 10, 0, 40), resizingMode: UIImageResizingMode.stretch)

        self.bgImgView = UIImageView.init()
        self.bgImgView?.image = image
        self.contentView.addSubview(self.bgImgView!)
        self.bgImgView?.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(249.5)
            make.centerX.equalToSuperview()
        }
        
//        self.titleLabel = UILabel.init()
//         self.titleLabel?.text = "选择存款方式"
//        self.titleLabel?.textColor = UIColor.white
//        self.titleLabel?.textAlignment = .center
//        self.titleLabel?.font = UIFont.systemFont(ofSize: 15)
//        self.bgImgView?.addSubview(self.titleLabel!)
//        self.titleLabel?.snp.makeConstraints{(make) in
//            make.width.equalTo(100)
//            make.height.equalTo(20)
//            make.centerX.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-60)
//        }
//
//
//
//
//        self.lineLView = UIView.init()
//        self.lineLView?.backgroundColor = UIColor.white
//         self.bgImgView?.addSubview(self.lineLView!)
//        self.lineLView?.snp.makeConstraints{(make) in
//            make.width.equalTo(100)
//            make.height.equalTo(0.5)
//            make.right.equalTo((titleLabel?.snp.left)!).offset(-5)
//            make.centerY.equalTo((self.titleLabel?.snp.centerY)!)
//        }
//
//
//        self.lineRView = UIView.init()
//        self.lineRView?.backgroundColor = UIColor.white
//        self.bgImgView?.addSubview(self.lineRView!)
//        self.lineRView?.snp.makeConstraints{(make) in
//            make.width.equalTo(100)
//            make.height.equalTo(0.5)
//            make.left.equalTo((titleLabel?.snp.right)!).offset(5)
//            make.centerY.equalTo((self.titleLabel?.snp.centerY)!)
//        }
//
//        self.iconImgView = UIImageView.init()
//        self.iconImgView?.image = imageNamed("icon_depoist_type_list_head_icon")
//        self.bgImgView?.addSubview(self.iconImgView!)
//        self.iconImgView?.snp.makeConstraints{(make) in
//            make.width.equalTo(91.5)
//            make.height.equalTo(93.5)
//            make.centerX.equalToSuperview()
//            make.bottom.equalTo((self.titleLabel?.snp.top)!).offset(-10)
//        }
//
        let searchView = UIView.init()
        searchView.backgroundColor = .white
        searchView.layer.shadowOpacity = 0.5
        searchView.layer.cornerRadius = 5
        searchView.layer.shadowRadius = 2;
        searchView.layer.shadowOffset = CGSize.init(width: 1, height: 1)
        self.contentView.addSubview(searchView)
        searchView.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-30)
            make.top.equalToSuperview().offset(15)
            make.bottom.equalToSuperview().offset(-65)
//            make.centerY.equalTo(self.contentView)
            make.centerX.equalTo(self.contentView)
        }
        let moneyIcon = UIImageView.init()
        moneyIcon.image = imageNamed("icon_withdraw_money")
        searchView.addSubview(moneyIcon)
        moneyIcon.snp.makeConstraints{(make) in
            make.width.equalTo(25)
            make.height.equalTo(25)
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(15)
        }
        let moneyLabel = UILabel.init()
        moneyLabel.text = "充值金额"
        moneyLabel.textColor = HexRGBAlpha(0x333333, 1)
        moneyLabel.font = UIFont.systemFont(ofSize: 18)
        moneyLabel.textAlignment = NSTextAlignment.left
        searchView.addSubview(moneyLabel)
        moneyLabel.snp.makeConstraints{(make) in
            make.width.equalTo(100)
            make.left.equalTo(moneyIcon.snp_right).offset(10)
            make.top.equalTo(moneyIcon.snp_top)
            make.bottom.equalTo(moneyIcon.snp_bottom)
        }
        editMoney = UITextField.init()
        editMoney?.placeholder = "请输入充值金额"
        editMoney?.keyboardType = .numberPad
        editMoney?.delegate = self
        editMoney?.font = UIFont.systemFont(ofSize: 18)
        editMoney?.borderStyle = .none
        editMoney?.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        searchView.addSubview(editMoney!)
        editMoney?.snp.makeConstraints{(make) in
            make.left.equalTo(moneyLabel.snp_left)
            make.right.equalTo(searchView.snp_right)
            make.height.equalTo(50)
            make.bottom.equalTo(searchView.snp_bottom).offset(-60)
        }
        let inputLine = UIView.init()
        inputLine.backgroundColor = UIColor.init("#dddddd")
        searchView.addSubview(inputLine)
        inputLine.snp.makeConstraints{(make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(editMoney!.snp_bottom)
        }
        let width = (UIScreen.main.bounds.width-72)/5
        let btn1 = UILabel.init()
        btn1.text = "50"
        btn1.font = UIFont.boldSystemFont(ofSize: 15)
        btn1.layer.cornerRadius = 5
        btn1.layer.masksToBounds = true
        btn1.textAlignment = .center
        btn1.textColor = .white
        btn1.backgroundColor = UIColor.init("#e9e9e9")
        btn1.isUserInteractionEnabled = true
        let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(money1))
        btn1.addGestureRecognizer(tap1)
        searchView.addSubview(btn1)
        btn1.snp.makeConstraints{(make) in
            make.width.equalTo(width)
            make.left.equalTo(searchView.snp_left).offset(7)
            make.bottom.equalToSuperview().offset(-12)
            make.top.equalTo(inputLine.snp_bottom).offset(12)
        }
        
        let btn2 = UILabel.init()
        btn2.text = "2000"
        btn2.layer.cornerRadius = 5
         btn2.font = UIFont.boldSystemFont(ofSize: 15)
        btn2.textColor = .white
        btn2.layer.masksToBounds = true
        btn2.textAlignment = .center
        btn2.backgroundColor = UIColor.init("#e9e9e9")
        btn2.isUserInteractionEnabled = true
        let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(money2))
        btn2.addGestureRecognizer(tap2)
        searchView.addSubview(btn2)
        btn2.snp.makeConstraints{(make) in
            make.width.equalTo(width)
            make.left.equalTo(btn1.snp_right).offset(7)
            make.bottom.equalToSuperview().offset(-12)
            make.top.equalTo(inputLine.snp_bottom).offset(12)
        }
        
        let btn3 = UILabel.init()
        btn3.text = "5000"
         btn3.font = UIFont.boldSystemFont(ofSize: 15)
        btn3.layer.cornerRadius = 5
        btn3.layer.masksToBounds = true
        btn3.textAlignment = .center
        btn3.textColor = .white
        btn3.backgroundColor = UIColor.init("#e9e9e9")
        btn3.isUserInteractionEnabled = true
        let tap3 = UITapGestureRecognizer.init(target: self, action: #selector(money3))
        btn3.addGestureRecognizer(tap3)
        searchView.addSubview(btn3)
        btn3.snp.makeConstraints{(make) in
            make.width.equalTo(width)
            make.left.equalTo(btn2.snp_right).offset(7)
            make.bottom.equalToSuperview().offset(-12)
            make.top.equalTo(inputLine.snp_bottom).offset(12)
        }
        
        let btn4 = UILabel.init()
        btn4.text = "20000"
         btn4.font = UIFont.boldSystemFont(ofSize: 15)
        btn4.layer.cornerRadius = 5
        btn4.layer.masksToBounds = true
        btn4.textAlignment = .center
        btn4.textColor = .white
        btn4.backgroundColor = UIColor.init("#e9e9e9")
        btn4.isUserInteractionEnabled = true
        let tap4 = UITapGestureRecognizer.init(target: self, action: #selector(money4))
        btn4.addGestureRecognizer(tap4)
        searchView.addSubview(btn4)
        btn4.snp.makeConstraints{(make) in
            make.width.equalTo(width)
            make.left.equalTo(btn3.snp_right).offset(7)
            make.top.equalTo(inputLine.snp_bottom).offset(12)
            make.bottom.equalToSuperview().offset(-12)
        }
        
        let btn5 = UILabel.init()
        btn5.text = "50000"
         btn5.font = UIFont.boldSystemFont(ofSize: 15)
        btn5.layer.cornerRadius = 5
        btn5.layer.masksToBounds = true
        btn5.textAlignment = .center
        btn5.textColor = .white
        btn5.isUserInteractionEnabled = true
        btn5.backgroundColor = UIColor.init("#e9e9e9")
        let tap5 = UITapGestureRecognizer.init(target: self, action: #selector(money5))
        btn5.addGestureRecognizer(tap5)
        searchView.addSubview(btn5)
        btn5.snp.makeConstraints{(make) in
            make.width.equalTo(width)
            make.left.equalTo(btn4.snp_right).offset(7)
            make.right.equalToSuperview().offset(-7)
            make.bottom.equalToSuperview().offset(-12)
            make.top.equalTo(inputLine.snp_bottom).offset(12)
        }
        
        
        self.bgItemView = UIView.init()
        self.bgItemView?.backgroundColor = UIColor.white
        self.contentView.addSubview(bgItemView!)
        self.bgItemView?.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-30)
            make.height.equalTo(20)
            make.bottom.equalToSuperview()
            make.centerX.equalTo(self.contentView)
        };
        self.bgItemBtn =  UIButton(type: UIButton.ButtonType.custom)//icon_my_cell_center  //icon_my_cell_top
        self.bgItemBtn?.setBackgroundImage(imageNamed("icon_my_cell_item")?.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 30, bottom: 5, right: 30),resizingMode: .stretch), for:UIControl.State.normal)
        
        self.contentView.addSubview(bgItemBtn!)
        self.bgItemBtn?.isHighlighted = false
        self.bgItemBtn?.adjustsImageWhenHighlighted = false
        self.bgItemBtn?.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-20)
            make.height.equalTo(60)
            make.bottom.equalToSuperview()
            make.centerX.equalTo(self.contentView)
        };
        
        self.tagView = UIView.init()
                self.bgItemBtn?.addSubview(tagView!)
                self.tagView?.snp.makeConstraints{(make) in
                    make.width.equalTo(70)
                    make.height.equalTo(22)
                    make.top.equalToSuperview().offset(5)
                    make.right.equalToSuperview().offset(-5)
                }
                self.tagImageView = UIImageView.init()
                self.tagImageView?.image = imageNamed("deposi_tag")?.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 30, bottom: 5, right: 30),
                resizingMode: .stretch)
                tagView?.addSubview(self.tagImageView!)
                self.tagImageView?.snp.makeConstraints{(make) in
                    make.width.equalToSuperview()
                    make.height.equalToSuperview()
        //            make.top.equalToSuperview().offset(5)
        //            make.right.equalToSuperview().offset(-5)
                }
               self.tagName = UILabel.init()
               self.tagName?.text = "限时存款"
               self.tagName?.textColor = HexRGBAlpha(0xffffff, 1)
               self.tagName?.font = UIFont.systemFont(ofSize: 12)
                self.tagName?.textAlignment = NSTextAlignment.left
               self.tagView?.addSubview(self.tagName!)
               self.tagName?.snp.makeConstraints{(make) in
        //             make.left.equalTo((self.tagImageView?.snp.right)!)
        //             make.right.equalTo((self.tagImageView?.snp.right)!)
        //             make.width.equalToSuperview()
                make.top.equalToSuperview().offset(2)
        //            make.left.equalToSuperview()
        //            make.height.equalToSuperview()
                    make.centerX.equalToSuperview()
                }
        tagView?.isHidden = true
        self.itemIconImgView = UIImageView.init()
      //  self.itemIconImgView?.image = imageNamed("icon_depoist_type_list_online_banking")
        self.bgItemBtn?.addSubview(self.itemIconImgView!)
        self.itemIconImgView?.snp.makeConstraints{(make) in
            make.left.equalToSuperview().offset(12)
            make.width.equalTo(25)
            make.height.equalTo(25)
            make.centerY.equalTo(self.bgItemBtn!)
        }
        self.itemTitleLabel = UILabel.init()
    //    self.itemTitleLabel?.text = "网银"
        self.itemTitleLabel?.textColor = HexRGBAlpha(0x333333, 1)
        self.itemTitleLabel?.font = UIFont.systemFont(ofSize: 15)
        self.itemTitleLabel?.textAlignment = NSTextAlignment.left
        self.bgItemBtn?.addSubview(self.itemTitleLabel!)
        
        self.itemTitleLabel?.snp.makeConstraints{(make) in
            make.left.equalTo((self.itemIconImgView?.snp.right)!).offset(12)
            make.width.equalToSuperview().offset(-70)
            make.height.equalTo(51)
            make.centerY.equalTo(self.bgItemBtn!)
        }
        
        //9 15
       // 15 9
        self.arrowImgView = UIImageView.init()
        self.arrowImgView?.image = imageNamed("icon_depoist_cell_arrow")
        self.bgItemBtn?.addSubview(self.arrowImgView!)
        
        self.arrowImgView?.snp.makeConstraints{(make) in
            make.right.equalToSuperview().offset(-12)
            make.width.equalTo(9)
            make.centerY.equalTo(self.bgItemBtn!)
            make.height.equalTo(15)
        }
        
        self.lineView = UIView.init()
        self.lineView?.backgroundColor = HexRGBAlpha(0xF3F3F3, 1)
        self.lineView?.isHidden = true
        self.bgItemBtn?.addSubview(self.lineView!)
        
        self.lineView?.snp.makeConstraints{(make) in
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-10)
            make.height.equalTo(0.7)
            make.bottom.equalToSuperview()
        }
    }
   
    
    func setData(dict:[String:Any]?) -> Void {
        if dict == nil {
            bgItemBtn?.isHidden = true
        }else{
            bgItemBtn?.isHidden = false
            let infoDict :[String:Any] = dict?["showInfo"] as? [String : Any] ?? [String:Any]()
            let optionid = infoDict["optionid"] as! String
            let dataDict = dict?[optionid] as? [String:Any] ?? [String:Any]()
            var rangeLimit = dataDict["rangeLimit"] as? String ?? ""
            if(rangeLimit == ""){
                let arrays = dict?[optionid] as? [[String:Any]] ?? [[String:Any]]()
                let temp = arrays[0] as? [String:Any] ?? [String:Any]()
                for (key, value) in temp {
                    if(key != "showInfo"){
                        let values = temp[key] as? [String:Any] ?? [String:Any]()
                        rangeLimit = values["rangeLimit"] as? String ?? ""
                        break
                    }
                }
            }
             var tagNames : String = infoDict["tag_name"] as? String ?? ""
            print("Deposit=====\(rangeLimit)===\(dict)===\(tagNames)")
            if(tagNames != ""){
                tagView?.isHidden = false
                tagName?.text = tagNames
            }else{
                tagView?.isHidden = true
            }
            let money = rangeLimit.components(separatedBy: ",")
            let min = money[0]
            let max = money[1]
            let showName = infoDict["show_name"] as? String ?? ""
            
            let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()
            let nameAttrs : [ NSAttributedString.Key:Any] = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15)]
            let name = NSAttributedString.init(string: showName, attributes: nameAttrs)
            let minAttrs : [ NSAttributedString.Key:Any] = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 12)]
            let minStr = NSAttributedString.init(string: "(最小:\(min),最大:\(max))", attributes: minAttrs)
            attributedStrM.append(name)
            attributedStrM.append(minStr)
            self.itemTitleLabel?.attributedText = attributedStrM
            
//            self.titleLabel?.text = "\(showName)(最小:\(min),最大:\(max))"
//            self.itemTitleLabel?.text = infoDict["show_name"] as? String ?? ""
            self.itemIconImgView?.sd_setImage(with: URL.init(string: infoDict["image_url"] as? String ?? ""), completed: nil)
        }
      
    }
    
    @objc func editingChanged(){
        cancel(task)
        self.task = delay(0.8) {
            self.delegate?.getMoney(money: self.editMoney?.text ?? "")
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let allowedCharacters = CharacterSet.init(charactersIn: "0123456789")
        let characterSet = CharacterSet.init(charactersIn: string)
        if(!allowedCharacters.isSuperset(of: characterSet)){
            return false
        }
        let max = 9
        let current = textField.text?.count ?? 0
        if(range.length+range.location > current){
            return false
        }
        let newLength = current + string.count - range.length
        
        return newLength <= max
    }
    
    @objc func money1(){
        editMoney?.text = "100"
        cancel(task)
        delegate?.getMoney(money: editMoney?.text ?? "")
    }
    @objc func money2(){
           editMoney?.text = "200"
        cancel(task)
        delegate?.getMoney(money: editMoney?.text ?? "")
       }
    @objc func money3(){
           editMoney?.text = "1000"
        cancel(task)
        delegate?.getMoney(money: editMoney?.text ?? "")
       }
    @objc func money4(){
           editMoney?.text = "3000"
        cancel(task)
        delegate?.getMoney(money: editMoney?.text ?? "")
       }
    @objc func money5(){
           editMoney?.text = "5000"
        cancel(task)
        delegate?.getMoney(money: editMoney?.text ?? "")
       }
    
    func clearMoney(){
         self.editMoney?.text = ""
    }
    
    typealias Task = (_ cancel: Bool) ->()
    func delay(_ time: TimeInterval, task: @escaping ()->()) -> Task? {
        func dispatch_later(block: @escaping ()->()) {
            let t = DispatchTime.now() + time
            DispatchQueue.main.asyncAfter(deadline: t, execute: block)
        }
    var closure: (()->())? = task
    var result: Task?
    let delayedClosure: Task = { cancel in
        if let internalClosure = closure {
            if cancel == false {
                DispatchQueue.main.async(execute: internalClosure)
            }
        }
        closure = nil
        result = nil
        }
    result = delayedClosure
    dispatch_later {
    if let delayedClosure = result {
            delayedClosure(false)
        }
    }
    return result
    }
    func cancel(_ task: Task?) {
        task?(true)
    }
}
